const Router = require('koa-router')()
const mongoose = require('mongoose')

Router.post('/add', async (ctx) => {
  // const iid = ctx.request.body
  // const count = ctx.request.body.count
  const body = ctx.request.body
  const phone = ctx.session.phone
  const table = mongoose.model('bee')
  if (body.count == 1) {
    try {
      await table.findOneAndUpdate({ phone }, { $push: { cartList: body } }, { useFindAndModify: false })
      ctx.body = {
        code: 200,
        msg: '成功'
      }
    } catch (err) {
      console.log(err)
      ctx.body = {
        code: 401,
        msg: '出现异常'
      }
    }
  } else {
    try {
      await table.updateOne({ phone, 'cartList.iid': body.iid }, { $set: { 'cartList.$.count': body.count } })
      console.log('sssss')
      ctx.body = {
        code: 200,
        msg: '商品数量加一'
      }
    } catch (err) {
      console.log(err)
      ctx.body = {
        code: 401,
        msg: '出现异常'
      }
    }
  }
  // ctx.body = {
  //   code: 200,
  //   body: body
  // }
})
Router.post('/remove', async (ctx) => {
  const ids = ctx.request.body.ids
  const phone = ctx.session.phone
  const table = mongoose.model('bee')
  try {
    await ids.forEach(async item => {
      try {
        await table.updateOne({ phone }, { $pull: { cartList: { iid: item } } }, { useFindAndModify: false, multi: true })
      } catch (err) {
        console.log(err)
        ctx.body = {
          code: 402,
          msg: '失败l'
        }
      }
    })
    ctx.body = {
      code: 200,
      msg: '删除成功'
    }
  } catch (err) {
    console.log(err)
    ctx.body = {
      code: 401,
      msg: '未知错误'
    }
  }
})
Router.post('/goodCount', async (ctx) => {
  const count = ctx.request.body.count
  const iid = ctx.request.body.iid
  const phone = ctx.session.phone
  const table = mongoose.model('bee')
  console.log(count, iid)
  try {
    await table.updateOne({ phone, 'cartList.iid': iid }, { $set: { 'cartList.$.count': count } })
    ctx.body = {
      code: 200,
      msg: '修改成功'
    }
  } catch (err) {
    console.log(err)
    ctx.body = {
      code: 400,
      msg: '发生错误'
    }
  }
})
module.exports = Router
